<template>
  <div id="trainEditTable">
    <el-form :model="addForm" :rules="addFormRules" ref="addForm">
      <table cellspacing="0" cellpadding="0" class="mytable">
        <!-- <tr v-if="type==='official'">
          <th width="100px">人选类型</th>
          <td colspan="3">
            <el-form-item label="" prop="type">
              <el-radio-group v-model="addForm.type">
                <el-radio :label="1">参训人选</el-radio>
                <el-radio :label="2">备选人选</el-radio>
              </el-radio-group>
            </el-form-item>
          </td>
        </tr> -->
        <tr>
          <th width="100px">单位</th>
          <td colspan="3">
            <el-form-item label="" prop="unit">
              <el-select filterable v-model="addForm.unit" placeholder="请选择" style="width:500px">
                <el-option v-for="item in unitList" :key="item.unitName" :label="item.unitName" :value="item.unitName"></el-option>
              </el-select>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th width="100px">姓名</th>
          <td width="500px">
            <el-form-item label="" prop="name">
              <el-input v-model="addForm.name" auto-complete="off" style="width:200px;" :maxlength="20"></el-input>
            </el-form-item>
          </td>
          <th width="100px">身份证号</th>
          <td width="500px">
            <el-form-item label="" prop="idCardNo">
              <el-input v-if="!addFlag" v-model="addForm.idCardNo" auto-complete="off" style="width:200px;" :maxlength="20"></el-input>
              <span v-else>{{addForm.idCardNo}}</span>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th>职务</th>
          <td>
            <el-form-item label="" prop="job">
              <el-input v-model="addForm.job" auto-complete="off" style="width:200px;" :maxlength="40"></el-input>
            </el-form-item>
          </td>
          <th>级别</th>
          <td>
            <el-form-item label="" prop="level">
              <el-input v-model="addForm.level" auto-complete="off" style="width:200px;" :maxlength="40"></el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th>是否党员</th>
          <td>
            <el-form-item label="" prop="partyMember">
              <el-select v-model="addForm.partyMember" placeholder="请选择" style="width:100px">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </td>
          <th>任相当层次职务职级时间</th>
          <td>
            <el-form-item label="" prop="jobDate">
              <!-- <el-date-picker v-model="addForm.jobDate" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" /> -->
              <el-input v-model="addForm.jobDate" auto-complete="off" style="width:150px;" :maxlength="8"></el-input>
              <el-tooltip class="item" effect="dark" content="格式：20201001或202010" placement="top">
                <el-button type="text" icon="el-icon-info" />
              </el-tooltip>
            </el-form-item>
          </td>
        </tr>
        <!-- <tr v-if="type==='official'||type==='recommended'">
          <th>备注</th>
          <td colspan="3">
            <el-form-item label="" prop="remarks">
              <el-input v-model="addForm.remarks" auto-complete="off" style="width:500px;" :maxlength="50"></el-input>
            </el-form-item>
          </td>
        </tr> -->
        <!-- <template v-if="type==='filed'">
          <tr>
            <th>参训时间</th>
            <td>
              <el-radio-group v-model="dateType">
                <el-radio :label="1">日期明确</el-radio>
                <el-date-picker v-if="dateType===1" key="trainingDate" v-model="addForm.trainingDate" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"  />
                <div style="clear:both" />
                <el-radio :label="2">日期不明确</el-radio>
                <template v-if="dateType===2">
                  <el-input placeholder="参训时间描述" v-model="addForm.trainingDateRemark" auto-complete="off" style="width:300px;" :maxlength="50"></el-input>
                  <el-date-picker key="trainingYear" v-model="addForm.trainingYear" placeholder="选择参训年份" type="year" format="yyyy" value-format="yyyy"  />
                </template>
              </el-radio-group>
            </td>
            <th>举办单位</th>
            <td>
              <el-form-item label="" prop="trainUnit">
                <el-input v-model="addForm.trainUnit" auto-complete="off" style="width:300px;" :maxlength="50"></el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th>班次名称</th>
            <td>
              <el-form-item label="" prop="className">
                <el-input v-model="addForm.className" auto-complete="off" style="width:300px;" :maxlength="50"></el-input>
              </el-form-item>
            </td>
            <th>参训地点</th>
            <td>
              <el-form-item label="" prop="place" >
                <el-input v-model="addForm.place" auto-complete="off" style="width:300px;" :maxlength="50"></el-input>
              </el-form-item>
            </td>
          </tr>
        </template> -->
      </table>
    </el-form>
    <el-button type="primary" style="margin-left:10px" :loading="addLoading" @click="submitForm(false)">保存</el-button>
  </div>
</template>

<script>
export default {
  watch: {
    timestamp: {
      handler (val) {
        if (!this.personId) {
          this.addFlag = false
          this.addForm = {
            type: null,
            unit: '',
            name: '',
            idCardNo: '',
            job: '',
            level: '',
            partyMember: '',
            jobDate: '',
            trainingDate: '',
            trainingDateRemark: '',
            trainingYear: '',
            trainUnit: '',
            className: '',
            place: '',
            remarks: ''
          }
        } else {
          this.getPersonInfoById(this.personId)
        }
      },
      immediate: true
    },
    deptId: {
      handler (val) {
        if (val) {
          this.getUnitList()
        }
      },
      immediate: true
    },
    // personId: {
    //   handler (val) {
    //     if (val) {
    //       this.getPersonInfoById(val)
    //     }
    //   },
    //   immediate: true
    // },
    type: {
      handler (val) {
        if (val !== 'filed') {
          this.viewtype = 2
        }
      },
      immediate: true
    }
  },
  props: {
    type: null,
    deptId: null,
    personId: null,
    classId: null,
    timestamp: null,
    id: null
  },
  data () {
    return {
      addFlag: false,
      unitList: [],
      dateType: 1,
      personDetailVisible: false,
      showManage: false,
      exportVisible: false,
      exportForm: {
        year: null,
        team: null
      },
      btnLoading: false,
      addFormTitle: '新增',
      loading: false,
      userType: null,
      showClassId: null,
      totalnum: 0,
      viewtype: 1,
      personList: [
      ],
      saveLoading: false,
      teams: ['机关司局', '直属单位', '派出机构'],
      yearlist: [],
      listLoading: false,
      pageNum: 1,
      pageSize: 20,
      changeSizeFlag: false,
      addLoading: false,
      classVisible: false,
      addFormVisible: false,
      addForm: {
        type: null,
        unit: '',
        name: '',
        idCardNo: '',
        job: '',
        level: '',
        partyMember: '',
        jobDate: '',
        trainingDate: '',
        trainingDateRemark: '',
        trainingYear: '',
        trainUnit: '',
        className: '',
        place: '',
        remarks: ''
      },
      addFormRules: {
        unit: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        idCardNo: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        job: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        partyMember: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        jobDate: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    getPersonInfoById (id) {
      this.$http
        .get(this.$http.defaults.trainingAPI + `api/trainingAdditionalPerson/getById?id=` + id)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.addForm.unit = response.data.result.unit
            this.addForm.name = response.data.result.name
            this.addForm.idCardNo = response.data.result.idCardNo
            this.addForm.age = response.data.result.age
            this.addForm.job = response.data.result.job
            this.addForm.level = response.data.result.level
            this.addForm.partyMember = response.data.result.partyMember
            this.addForm.jobDate = response.data.result.jobDate
            this.addForm.id = response.data.result.id
            this.addFlag = true
          }
        })
        .catch((error) => {
          this.loading = false
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    getUnitList () {
      let belongDept = null
      belongDept = this.deptId
      let para = {
        'belongDept': belongDept,
        'pageNum': 1,
        'pageSize': 1000
      }
      this.$http.post(this.$http.defaults.trainingAPI + `api/trainingBusUnit/queryByPage`, para).then(response => {
        if (response.data.success === true) {
          this.unitList = response.data.result.records
        } else {
          this.$message({
            message: '获取失败:' + response.data.message,
            type: 'error'
          })
        }
      }).catch((error) => {
        console.log(error)
        this.$message({
          message: '获取失败:' + error,
          type: 'error'
        })
      })
    },
    isDate8 (sDate) {
      if (!/^[0-9]{8}$/.test(sDate)) {
        return false
      }
      var year, month, day
      year = sDate.substring(0, 4)
      month = sDate.substring(4, 6)
      day = sDate.substring(6, 8)
      var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      if (year < 1700 || year > 2500) return false
      if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) iaMonthDays[1] = 29
      if (month < 1 || month > 12) return false
      if (day < 1 || day > iaMonthDays[month - 1]) return false
      return true
    },
    isDate6 (sDate) {
      if (!/^[0-9]{6}$/.test(sDate)) {
        return false
      }
      var year, month
      year = sDate.substring(0, 4)
      month = sDate.substring(4, 6)
      if (year < 1700 || year > 2500) return false
      if (month < 1 || month > 12) return false
      return true
    },
    submitForm (flag) {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          console.log(this.addForm.jobDate)
          if (!this.isDate8(this.addForm.jobDate) && !this.isDate6(this.addForm.jobDate) && this.addForm.jobDate) {
            this.$message({
              message: '任相当层次职务职级时间保存失败：格式有误，格式：20201001或202010',
              type: 'error'
            })
            return false
          }
          let para = {
            id: this.addForm.id,
            unit: this.addForm.unit,
            name: this.addForm.name,
            idCardNo: this.addForm.idCardNo,
            job: this.addForm.job,
            level: this.addForm.level,
            jobDate: this.addForm.jobDate,
            partyMember: this.addForm.partyMember,
            addFlag: this.addFlag ? this.addFlag : flag
            // remarks: this.addForm.remarks,
            // trainingDate: this.dateType === 1 ? this.addForm.trainingDate : '',
            // trainingDateRemark: this.dateType === 2 ? this.addForm.trainingDateRemark : '',
            // trainingYear: this.dateType === 2 ? parseInt(this.addForm.trainingYear) : (this.addForm.trainingDate ? this.dateFtt('yyyy', this.addForm.trainingDate) : ''),
            // trainUnit: this.addForm.trainUnit,
            // className: this.addForm.className,
            // place: this.addForm.place
          }
          // if (this.dateType === 2 && (!this.addForm.trainingDateRemark || !this.addForm.trainingYear)) {
          //   this.$message({
          //     message: '参训日期不明确时请填写参训日期描述和参训年份',
          //     type: 'error'
          //   })
          //   return false
          // }
          // if (this.dateType === 1 && !this.addForm.trainingDate) {
          //   this.$message({
          //     message: '请填写参训日期',
          //     type: 'error'
          //   })
          //   return false
          // }
          this.addLoading = true
          this.$http.post(this.$http.defaults.trainingAPI + `api/trainingAdditionalPerson/save`, para).then(response => {
            console.log(response.data.success)
            if (response.data.success === true) {
              this.addForm.age = response.data.result
              // this.addToCandidate(this.addForm)

              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.addLoading = false
              this.$emit('refreshRecommented')
            } else {
              this.addLoading = false
              if (response.data.message === '发生错误：该身份证号已存在') {
                this.$confirm('您输入的身份证号已存在，是否更新该人员信息', '提示', {
                  type: 'warning'
                }).then(() => {
                  this.submitForm(true)
                }).catch(() => {
                  this.addFormVisible = false
                })
              } else {
                console.log('保存失败:' + response.data.message)
                this.$message({
                  message: '保存失败:' + response.data.message,
                  type: 'error'
                })
              }
            }
          }).catch(error => {
            console.log(error)
            this.$message({
              message: '保存失败:' + error,
              type: 'error'
            })
            this.addLoading = false
          })
        }
      })
    },
    addToCandidate (data) {
      let type = this.addForm.type
      this.$http
        .get(this.$http.defaults.trainingAPI + `api/trainingBusClass/getById?id=` + this.classId)
        .then(response => {
          if (response.data.success === true) {
            let tableName = 'trainingBusRecommendedCandidate'
            if (type) {
              tableName = 'trainingBusOfficialCandidate'
            }
            let batchId = response.data.result.batchId
            let personNumber = response.data.result.personNumber
            let para = {
              batchId: batchId,
              classId: this.classId,
              deptId: this.deptId,
              name: data.name,
              idCardNo: data.idCardNo,
              age: data.age,
              unit: data.unit,
              job: data.job,
              level: data.level,
              partyMember: data.partyMember,
              jobDate: data.jobDate,
              remarks: data.remarks,
              selected: false
            }
            if (type) {
              para.type = type
              para.participation = (type === 1 ? 1 : 0)
            }
            if (type === 1) {
              this.$http
                .get(this.$http.defaults.trainingAPI + `api/trainingBusClass/getOfficialCandidateList?classId=` + this.classId)
                .then(response => {
                  if (response.data.success === true) {
                    let officialNum = response.data.result.filter(item => item.type === 1 && item.participation).length
                    if (officialNum < personNumber) {
                      this.addToCandidateSubmit(para, tableName)
                    } else {
                      this.$confirm('该班次培训人数为' + personNumber + '人，已添加参训人员' + officialNum + '人，是否继续添加？', '提示', {
                        type: 'warning'
                      }).then(() => {
                        this.addToCandidateSubmit(para, tableName)
                      }).catch(() => {
                        this.addLoading = false
                      })
                    }
                  } else {
                    this.addLoading = false
                    console.log('获取失败:' + response.data.message)
                    this.$message({
                      message: '获取失败:' + response.data.message,
                      type: 'error'
                    })
                  }
                })
                .catch((error) => {
                  this.addLoading = false
                  console.log(error)
                  this.$message({
                    message: '获取失败:' + error,
                    type: 'error'
                  })
                })
            } else {
              this.addToCandidateSubmit(para, tableName)
            }
          } else {
            this.addLoading = false
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.addLoading = false
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    addToCandidateSubmit (para, tableName) {
      this.$http.post(this.$http.defaults.trainingAPI + `api/` + tableName + `/save`, para).then(response => {
        console.log(response.data.success)
        this.addLoading = false
        if (response.data.success === true) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$emit('refreshRecommented')
        } else {
          console.log('操作失败:' + response.data.message)
          this.$message({
            message: '操作失败:' + response.data.message,
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '保存失败:' + error,
          type: 'error'
        })
        this.addLoading = false
      })
    },
    handleEditPerson () {
      if (this.type === 'recommended') {
        this.personVisible = true
      } else if (this.type === 'official') {
        this.personVisible1 = true
      }
    },
    inRoles (str) {
      let arr = JSON.parse(localStorage.getItem('Roles'))
      if (arr.indexOf(str) === -1) {
        return false
      } else {
        return true
      }
    },
    getDeptId () {
      let unitName = localStorage.getItem('unitName')
      let deptId = null
      switch (unitName) {
        case '干部一处':
          deptId = 1
          break
        case '干部二处':
          deptId = 2
          break
        case '干部三处':
          deptId = 3
          break
      }
      if (deptId) {
        this.userType = 2
        // this.userTeam = deptId
      }
      if (this.inRoles('ROLE_training')) {
        this.userType = 1
      }
      if (this.inRoles('ROLE_fusizhang')) {
        this.userType = 3
      }
      if (this.inRoles('ROLE_sizhang')) {
        this.userType = 4
        this.myAuth = 1
      }
    }
  },
  mounted () {
    this.getUnitList()
    this.getDeptId()
    if (localStorage.getItem('trainingAuth') === '1') {
      this.showManage = false
    } else {
      this.showManage = true
    }
  }
}
</script>
<style>
  #trainIndex .wboxd .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  #trainIndex .wboxd .el-table td,
  #train .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
  #trainIndex .el-table--border th,
  #train .el-table--border td {
    border-right: 1px solid #95B8E7;
  }
  #trainIndex .el-table th.is-leaf,
  #train .el-table td {
    border-bottom: 1px solid #95B8E7;
  }
  #trainIndex .el-table td{
    border-right: 1px solid #95B8E7;
    border-bottom: 1px solid #95B8E7;
  }
  .el-table .mark_class {
      background: rgb(253, 226, 226);
  }
</style>
<style scoped>
  #trainIndex h1{
    font-size:var(--size16) !important;
    font-weight: bolder;
    height: 30px;
    border-bottom: 1px solid #95B8E7;
    font-family: '宋体';
    line-height: 30px;
    color: #000;
    padding-left:10px;
    background-image: linear-gradient(to bottom , #EEF4FF, #E0ECFF);
    margin:0;
  }
  #trainIndex .el-pagination{
    float: left;
    padding:7px 10px;
  }
  #trainIndex .wboxs{
    padding:5px 15px;
    width: calc(100% - 30px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
  #trainIndex .wboxd{
    padding:0;
    width: calc(100% - 0px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
  #trainEditTable .el-upload--text{
    float:left !important;
  }
  #trainEditTable .el-upload__tip{
    float:left !important;
    margin-left:5px;
    margin-top:0 !important;
  }
  #trainEditTable .el-upload-list--text{
    padding-top:5px;
    clear: both !important;
  }
  .el-table{
    border-top: 1px solid #95B8E7 !important;
  }
  .el-table--border th, .el-table--border td {
    border-right: 1px solid #95B8E7 !important;
  }
  .el-table th.is-leaf, .el-table td {
    border-bottom: 1px solid #95B8E7 !important;
    border-right: 1px solid #95B8E7 !important;
  }
  #trainEditTable .mytable{
    border-top: 1px solid #74A6CC;
    border-left: 1px solid #74A6CC;
    margin: 10px;
    width: calc(100% - 20px);
    font-size:var(--size14) !important;
    font-family: '宋体'
  }
  #trainEditTable .mytable th,
  #trainEditTable .mytable td{
    height: auto;
    padding: 10px;
    border-right: 1px solid #74A6CC;
    border-bottom: 1px solid #74A6CC;
    vertical-align:top;
    line-height: 150%;
  }
  #trainEditTable .mytable th{
    background:#C0DCF1;
    width:150px;
    vertical-align: middle;
  }
</style>
